﻿@{
	Layout = "~/Views/Shared/_Layout.cshtml";
}

@section styles {
	<style type="text/css">
		.shopping-cart-list tbody tr td {
			vertical-align: middle;
		}
	</style>
}

@using dPet.Application.DataObjects;

<div ng-controller="SaleOrderController">
	<div class="page-header">
		<h3>创建销售订单 {{ membershipLevel.title }}</h3>
	</div>
	<div class="panel panel-default" ng-if="membershipLevel.value == ''">
		<div class="panel-heading">选择客户类别</div>
		<div class="panel-body text-center">
			<div class="btn-group btn-group-justified" style="max-width:500px; margin:0 auto;">
				<div class="btn-group btn-group-lg">
					<button type="button" class="btn btn-default" ng-click="setMembershipLevel('@MembershipLevelDto.None', '非会员')">非会员</button>
				</div>
				<div class="btn-group btn-group-lg">
					<button type="button" class="btn btn-default" ng-click="setMembershipLevel('@MembershipLevelDto.Normal', '普通会员')">普通会员</button>
				</div>
			</div>
		</div>
	</div>

	<div class="panel panel-default" ng-if="membershipLevel.value != ''">
		<div class="panel-heading">
			<form class="form-inline" ng-submit="findProductList()">
				<div class="input-group">
					<span class="input-group-addon">名称或标签</span>
					<input type="text" class="form-control input-sm" placeholder="请输入商品名称或标签" ng-model="productsSearched.nameOrTag" />
					<span class="input-group-btn">
						<button class="btn btn-info btn-sm" type="submit"><span class="glyphicon glyphicon-search"></span> 查 询</button>
					</span>
				</div>
				<button class="btn btn-info btn-sm" type="button" ng-click="showScanProductModal()"><span class="glyphicon glyphicon-barcode"></span> 扫 码</button>
			</form>
		</div>

		<table class="table table-striped text-center shopping-cart-list" ng-if="shoppingCart.length > 0">
			<thead>
				<tr>
					<th class="text-center">商品条码</th>
					<th class="text-center">商品名称</th>
					<th class="text-center">单价（元）</th>
					<th class="text-center" style="width:300px;">数量</th>
					<th class="text-center">小计（元）</th>
					<th class="text-center" style="width:150px;">操作</th>
				</tr>
			</thead>
			<tbody>
				<tr ng-repeat='item in shoppingCart'>
					<td>{{ item.Barcode }}</td>
					<td>{{ item.Name }}</td>
					<td>{{ item.UnitPrice | currency : '' }}</td>
					<td class='form-inline' style='text-align:left;'>
						<div class='input-group' style='width:110px;'>
							<span class='input-group-btn'><button class='btn btn-default btn-sm' type='button' ng-click="minusQuantity(item)">-</button></span>
							<input type='text' class='form-control input-sm' ng-model="item.Quantity" ng-change="quantityChanged(item)" />
							<span class='input-group-btn'><button class='btn btn-default btn-sm' type='button' ng-click="addQuantity(item)">+</button></span>
						</div>
						<span>&nbsp;{{ item.UnitName }}&nbsp;&nbsp;（库存：{{ item.InventoryCount }}&nbsp;{{ item.UnitName }}）</span>
					</td>
					<td>{{ (item.UnitPrice * item.Quantity) | currency : '' }}</td>
					<td><a href='javascript:;' ng-click='removeItemFromShoppingCart($index)'>删除</a></td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<td colspan="5">&nbsp;</td>
					<td><strong>总金额：<span>{{ calculateTotalAmount() | currency : '' }}</span> 元</strong></td>
				</tr>
			</tfoot>
		</table>

		<div class="panel-footer text-right" ng-if="shoppingCart.length > 0">
			<button type="button" class="btn btn-default btn-sm" ng-click="emptyShoppingCart()"><span class="glyphicon glyphicon-trash"></span> 清 空</button>
			<button type="button" class="btn btn-info btn-sm" ng-click="submitSaleOrder()"><span class="glyphicon glyphicon-file"></span> 下 单</button>
		</div>

		<div class="panel-body text-center" ng-if="shoppingCart.length == 0">
			<p>尚未添加任何商品</p>
		</div>
	</div>

	<div class="modal fade" id="scan_Modal" tabindex="-1" role="dialog" aria-hidden="true">
		<br /><br /><br /><br />
		<div class="modal-dialog modal-sm">
			<div class="modal-content">
				<form ng-submit="findProductByBarcode()">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
						<h4 class="modal-title">读取条码</h4>
					</div>
					<div class="modal-body">
						<input type="text" class="form-control" id="txt_barcode" placeholder="读取条码" ng-model="scanedBarcode" />
					</div>
				</form>
			</div>
		</div>
	</div>

	<div class="modal fade" id="product_list_Modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="false">
		<br /><br /><br /><br />
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					<h4 class="modal-title">商品列表</h4>
				</div>
				<div class="modal-body form-horizontal">
					<table class="table table-striped text-center">
						<thead>
							<tr>
								<th class="text-center">条码</th>
								<th class="text-center">名称</th>
								<th class="text-center">单价（元）</th>
								<th class="text-center">库存</th>
								<th class="text-center">操作</th>
							</tr>
						</thead>
						<tbody>
							<tr ng-repeat='product in productsSearched.products'>
								<td>{{ product.Barcode }}</td>
								<td>{{ product.Name }}</td>
								<td>{{ product.UnitPrice | currency : '' }}</td>
								<td>{{ product.InventoryCount }}&nbsp;{{ product.UnitName }}</td>
								<td><a href='javascript:;' ng-click='addProductIntoShoppingCart(product)'>选择</a></td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</div>

@section scripts {
	<script type="text/javascript">
		$(document).ready(function () {
			set_left_nav('#ln_CreateSaleOrder');
		});

		$('#scan_Modal').on('shown.bs.modal', function (e) {
			$('#txt_barcode').focus();
		});

		angular.module('dpet').controller('SaleOrderController', function ($scope, $http) {
			$scope.membershipLevel = { value: '', title: '' };
			$scope.productsSearched = { nameOrTag: '', products: [] };
			$scope.scanedBarcode = '';
			$scope.shoppingCart = [];

			//查找购物车中商品索引
			var existItemInShoppingCart = function (productId) {
				for (var i = 0; i < $scope.shoppingCart.length; i++) {
					if ($scope.shoppingCart[i].ItemId == productId)
						return true;
				}

				return false;
			}

			//设置会员等级
			$scope.setMembershipLevel = function (level, title) {
				$scope.membershipLevel.value = level;
				$scope.membershipLevel.title = "[ " + title + " ]";
			}

			$scope.findProductList = function () {
				$scope.productsSearched.products = [];

				if ($scope.productsSearched.nameOrTag == '')
					alert('请输入商品名称或商品标签');
				else {
					$http.post('/Ajax/ProductListForMembership',
						{
							'membershipLevel': $scope.membershipLevel.value,
							'NameOrTag': $scope.productsSearched.nameOrTag
						})
						.success(function (products) {
							if (products == null || products.length == 0) {
								alert("未找到对应商品");
								$scope.productsSearched.nameOrTag = '';
							}
							else {
								$scope.productsSearched.products = products;

								$('#product_list_Modal').modal('show');
							}
						})
						.error(function (result) {
							alert("系统繁忙");
						});
				}
			}

			//弹出扫码层
			$scope.showScanProductModal = function () {
				$('#scan_Modal').modal('show');
			}

			$scope.findProductByBarcode = function () {
				if ($scope.scanedBarcode == '') {
					alert('请读取条码');
					$("#txt_barcode").focus();
				}
				else {
					$http.post('/Ajax/ProductListForMembership',
						{
							'membershipLevel': $scope.membershipLevel.value,
							'Barcode': $scope.scanedBarcode
						})
						.success(function (products) {
							if (products == null || products.length == 0)
								alert("未找到对应商品");
							else
								$scope.addProductIntoShoppingCart(products[0]);
						})
						.error(function (result) {
							alert("系统繁忙");
						});

					$scope.scanedBarcode = '';
				}
			}

			//将商品添加至购物车
			$scope.addProductIntoShoppingCart = function (product) {
				if (product.InventoryCount == 0)
					alert("该商品库存不足");
				else if (existItemInShoppingCart(product.Id))
					alert('该商品已添加');
				else {
					$scope.shoppingCart.push({
						ItemId: product.Id,
						Barcode: product.Barcode,
						Name: product.Name,
						UnitPrice: product.UnitPrice,
						UnitName: product.UnitName,
						InventoryCount: product.InventoryCount,
						Quantity: 1
					});

					$('#scan_Modal').modal('hide');
					$('#product_list_Modal').modal('hide');
				}
			}

			//将商品移出购物车
			$scope.removeItemFromShoppingCart = function (index) {
				$scope.shoppingCart.splice(index, 1);
			}

			//清空购物车
			$scope.emptyShoppingCart = function () {
				if (confirm("是否要清空当前购物列表?")) {
					$scope.shoppingCart = [];
				}	
			}

			//计算总金额
			$scope.calculateTotalAmount = function () {
				var totalAmount = 0;

				angular.forEach($scope.shoppingCart, function (item) {
					totalAmount += item.Quantity * item.UnitPrice;
				});

				return totalAmount;
			}

			//减少商品数量
			$scope.minusQuantity = function (item) {
				if (item.Quantity > 1)
					item.Quantity--;
			}

			//增加商品数量
			$scope.addQuantity = function (item) {
				if (item.Quantity < item.InventoryCount)
					item.Quantity++;
			}

			//数量变更检测
			$scope.quantityChanged = function (item) {
				if (isNaN(item.Quantity) || item.Quantity < 1)
					item.Quantity = 1;
				else if (item.Quantity > item.InventoryCount)
					item.Quantity = item.InventoryCount;
			}

			//提交订单
			$scope.submitSaleOrder = function () {
				if ($scope.shoppingCart.length > 0 && confirm("确认下单?")) {
					$http.post('/SaleOrder/Create',
						{
							'items': $scope.shoppingCart,
							'membershipLevel': $scope.membershipLevel.value
						})
						.success(function (result) {
							alert(result.Message);

							if (result.Success)
								window.location.href = "/SaleOrder/Pay/" + result.OrderId;
						})
						.error(function (result) {
							alert("系统繁忙");
						});
				}
			}
		});
	</script>
}
